import React, { useImperativeHandle, useRef, useState } from 'react';
import { Button, Card, message, Modal, Progress, Space } from 'antd';
import { uploadSeatSoundRecord } from 'seats/servers/servers';
import Recorder from 'js-audio-recorder';
import { PauseCircleOutlined, PlayCircleOutlined } from '@ant-design/icons';
import { SeatSoundRecordInfo } from 'seats/schema/SoundManage';

type IProps = {
  cRef: any;
  templateId: number; //录音模板id
};

// 存储回调函数
let ok = () => {};

/**在线录音弹窗 */
const SoundRecord: React.FC<IProps> = ({ cRef, templateId }) => {
  const [soundRecordId, setSoundRecordId] = useState<any>(null); // 表单id
  const [soundInfo, setSoundInfo] = useState<any>({}); // 表单id

  const [recordStep, setRecordStep] = useState<number>(1); // 录音步骤
  const [visible, setVisible] = useState<boolean>(false);
  const [play, setPlay] = useState<number>(0); // 是否播放中，默认为false
  const [duration, setDuration] = useState<number>(0); // 录音时长
  const [playTime, setPlayTime] = useState<number>(0); // 录音播放时长
  const [percent, setPercent] = useState<number>(0); // 录音播放百分比
  const timer = useRef<any>(null); // 计时器存储
  const recorder = useRef<any>(null); // 存储录音对象

  const open = (obj: SeatSoundRecordInfo, cb: any) => {
    console.log(obj, '传递到弹窗的数据---');
    setVisible(true);
    ok = cb;
    const info = {
      script: obj.scriptContent,
      origin: obj.originalScripts,
    };
    setSoundInfo(info);
    setSoundRecordId(obj.soundRecordId);
  };

  useImperativeHandle(cRef, () => ({
    // 父组件数据和事件传递
    open: (obj: any, cb: any) => open(obj, cb),
  }));

  const handleRecord = () => {
    console.log('点击-开始录音,录音实例', recorder.current);
    setRecordStep(2);
    console.log('*******************新建录音实例-4.7');
    // 录音实例化
    recorder.current = new Recorder({
      // type: "wav", //此处的type类型是可修改的
      sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
      sampleRate: 8000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
      numChannels: 1, // 声道，支持 1 或 2， 默认是1
      compiling: false, // (0.x版本中生效,1.x增加中) 是否边录边转换，默认是false
    });
    recorder.current.start().then(
      () => {
        message.success('开始录音');
      },
      (error: any) => {
        // 出错了
        console.log(`${error.name} : ${error.message}`);
      }
    );
    // 回调-录音过程-持续输出时长
    recorder.current.onprogress = (params: any) => {
      // eslint-disable-next-line prefer-const
      let { duration, fileSize } = params;
      // console.log("录音时长(秒)", duration);
      // console.log("录音大小(字节)", fileSize);
      if (duration >= 10 * 60) {
        message.warning('录音时长最大为10分钟，已完成录音');
        recorder.current.stop();
      }
      if (fileSize >= 50 * 1024 * 1024) {
        message.warning('录音文件最大为50M，已完成录音');
        recorder.current.stop();
      }
      duration = duration.toFixed(2);
      setDuration(duration);
    };
    // 回调-录音开始播放
    recorder.current.onplay = () => {
      console.log('onplay');
      setPlay(1);
      setPlayTime(0);
      setPercent(0);
    };
    // 回调-录音播放暂停
    recorder.current.onpauseplay = () => {
      console.log('onpauseplay');
      setPlay(2);
    };
    // 回调-录音恢复播放
    recorder.current.onresumeplay = () => {
      console.log('onresumeplay');
      setPlay(1);
    };
    // 回调-录音播放停止
    recorder.current.onstopplay = () => {
      console.log('onstopplay');
      setPlay(0);
      setRecordStep(1);
      setDuration(0);
      setPlayTime(0);
      setPercent(0);
    };
    // 回调-录音播放完毕
    recorder.current.onplayend = () => {
      console.log('onplayend');
    };
  };
  const handleRecordDone = () => {
    message.success('录音完成');
    console.log('录音总时长', recorder.current.duration);
    recorder.current.stop();
    setRecordStep(3);
  };

  const timeCount = () => {
    // 计时器开始
    // playTime已播放时间
    // debugger;
    let time = playTime;
    if (play === 0) {
      // 点击开始，时间从0开始
      time = 0;
    }
    clearInterval(timer.current);
    timer.current = setInterval(() => {
      time = time + 1;
      const per = Math.round((time * 100) / duration);
      if (per >= 100) {
        message.success('播放结束');
        setPercent(100);
        setPlayTime(duration);
        setPlay(0);
        clearInterval(timer.current);
        return;
      }
      console.log('计时器-当前', time, duration);
      console.log('总长，百分比', duration, per);
      setPercent(per);
      setPlayTime(time);
    }, 1000); //单位：ms
  };

  const handlePlay = () => {
    // 录音播放
    recorder.current.play();
    message.success('开始播放');
    timeCount();
  };

  const handlePause = () => {
    // 播放暂停
    if (play === 1) {
      message.success('暂停播放');
      clearInterval(timer.current);
      recorder.current.pausePlay();
    }
    if (play === 2) {
      message.success('继续播放');
      recorder.current.resumePlay();
      timeCount();
    }
  };
  const handleReset = () => {
    // 重录
    console.log('点击-重录，录音停止，播放停止');
    recorder.current.stop();
    recorder.current.stopPlay();
    clearInterval(timer.current);
    // 销毁录音实例，释放资源，fn为回调函数，
    recorder.current.destroy().then(function () {
      console.log('********重录*****录音实例销毁');
      recorder.current = null;
    });
  };
  const handleClose = () => {
    // 关闭
    console.log('点击-关闭');
    if (recorder.current) {
      console.log('录音停止，播放停止');
      // 判断是否存在;1.未点击开始录音没有实例，2.重录按钮点击时没有实例
      recorder.current.stop();
      recorder.current.stopPlay();
      clearInterval(timer.current);
      // 销毁录音实例，释放资源，fn为回调函数，
      recorder.current.destroy().then(function () {
        console.log('************关闭*************录音实例销毁');
        recorder.current = null;
      });
    }
    // 恢复默认
    setSoundRecordId(null);
    setVisible(false);
  };
  /**
   * 时间处理函数
   * 返回例如 00:04 的时间格式
   * num:秒，如3.54s
   */
  const timeFormate = (num: number): string => {
    // 秒
    const seconds = Math.ceil(num);
    const min = Math.floor(seconds / 60);
    const minStr = min < 10 ? '0' + min : min + '';

    const second = seconds % 60;
    const secondStr = second < 10 ? '0' + second : second + '';

    return `${minStr}:${secondStr}`;
  };

  const handleOK = () => {
    // 上传录音文件
    console.log('保存录音-上传');
    // 测试-下载文件-查看文件音频数据
    // recorder.current.downloadWAV(["录音文件下载测试01"]);
    // if (true) {
    //   console.log("已下载录音文件");
    //   return;
    // }

    const recorderBlob = recorder.current.getWAVBlob();
    console.log('1.在线录音-blob', recorderBlob);
    // 关闭弹窗
    handleClose();
    const uploadFile = new File([recorderBlob], 'OnlineRecord.wav', {
      type: recorderBlob.type,
    });
    // 之后的流程：跟列表页面上传逻辑一致
    console.log('2.开始上传-在线录音-文件', uploadFile);
    const formData = new FormData();
    formData.append('file', uploadFile);
    formData.append('templateId', JSON.stringify(templateId));
    /**接口请求-上传录音文件 */
    uploadSeatSoundRecord(soundRecordId, formData)
      .then(res => {
        if (res.code === 0) {
          message.success('上传成功');
          // 执行回调刷新
          ok();
        }
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  };

  return (
    <Modal
      width={600}
      title="在线录音"
      visible={visible}
      onOk={handleOK}
      onCancel={handleClose}
      footer={null}
    >
      <div className="sound-record-title">
        <Card size="small" bordered={false} style={{ width: '100%' }}>
          <div className="box">【话术】{soundInfo.script}</div>
        </Card>
      </div>
      <div className="sound-record-box">
        <Card
          size="small"
          // title="录音"
          style={{ marginTop: 10, width: '100%' }}
        >
          {/* step1：录音 or 取消 */}
          {recordStep === 1 && (
            <>
              {/* 显示录音时长 */}
              <div className="time-count">{timeFormate(duration)}</div>
              <Space className="btn-wrap step1">
                <Button type="primary" onClick={handleRecord}>
                  开始录音
                </Button>
                <Button onClick={handleClose}>取消</Button>
              </Space>
            </>
          )}
          {/* step2：录音完成 or 重录回第一步 */}
          {recordStep === 2 && (
            <>
              {/* 显示录音时长 */}
              <div className="time-count">{timeFormate(duration)}</div>
              <Space className="btn-wrap step2">
                <Button type="primary" onClick={handleRecordDone}>
                  录音完成
                </Button>
                <Button onClick={handleReset}>重录</Button>
              </Space>
            </>
          )}
          {/* step3：展示播放按钮，保存按钮 or 重录回第一步 */}
          {recordStep === 3 && (
            <>
              {/* 显示录音播放 */}
              <div className="audio-wrap">
                <div className="playline">
                  <Progress percent={percent} size="small" />
                  <div className="time">
                    <span>{timeFormate(playTime)}</span>
                    <span>{timeFormate(duration)}</span>
                  </div>
                </div>
                {play ? (
                  // 播放中
                  <Button
                    type="link"
                    icon={<PauseCircleOutlined style={{ fontSize: 38 }} />}
                    onClick={handlePause}
                  ></Button>
                ) : (
                  // 播放前
                  <Button
                    type="link"
                    icon={<PlayCircleOutlined style={{ fontSize: 38 }} />}
                    onClick={handlePlay}
                  ></Button>
                )}
              </div>
              <Space className="btn-wrap step3">
                <Button type="primary" onClick={handleOK}>
                  保存录音
                </Button>
                <Button onClick={handleReset}>重录</Button>
              </Space>
            </>
          )}
        </Card>
      </div>
    </Modal>
  );
};

export default SoundRecord;
